
import cfmap from "cfmap-4490";
import highlightStyle from "./highlight-style.json";

export default function () {
    return {
        data() {
            return {
                mapConfig: {
                    center: [120.667663, 31.155515],
                    zoom: 11.68,
                    pitch: 0,
                    bearing: 0,
                    minZoom: 11,
                },
                baseMap: {
                    vector: {
                        id: 'basemap_vector',
                        url: process.env.VUE_APP_BASE_BASEMAP_DARK,
                    },
                    image: {
                        id: 'basemap_image',
                        url: process.env.VUE_APP_BASE_BASEMAP_IMAGE
                    },

                },

                /** 选中图标 */
                iconList: [

                ],
                iconList2: [

                ],
                iconMatch: [

                ],

                openDetailing: false,
                isFull: false,
            };
        },
        computed: {
        },
        watch: {
            lr_isCollapse() {
                setTimeout(() => {
                    this.mapboxmap.resize(); // 重新设置地图容器的尺寸
                }, 600);
            },
        },
        mounted() {
            window.addEventListener('resize', function () {
                this.mapboxmap.resize(); // 重新设置地图容器的尺寸
            });

        },
        beforeDestroy() {
            this.mapboxmap && this.mapboxmap.remove()
            this.mapboxmap = null
        },
        methods: {
            /** 数据格式化 */
            formatResultData(data) {
                var newData = data.map((elet, idx) => {
                    if (elet.geo) {
                        let ele = {
                            index: idx + 1, // 根据索引上图
                            geom: elet.geoPT,
                            geoPolygon: elet.geoJson,
                            geoType: elet.geoPT.type.toLowerCase() === 'polygon' ? '面' : '点',
                            origin: elet,
                            issueBigType: elet.issueBigType,
                            id: elet.id
                        };
                        return ele
                    }
                })
                return newData;
            },

            //#region 图层信息 符号图层


            /** 文本符号图层上图  */
            setMarkerLayer(geoJSON) {
                geoJSON.features.forEach(item => {
                    const marker = document.createElement("DIV");
                    marker.innerHTML = `
                        <div class="marker">
                            <span>社区总数：<span class="marker-num">${item.properties?.communityNumValue || 0}</span> 个</span>
                            <span>户籍老年人口数：<span class="marker-num">${item.properties?.streetPersonNumValue || 0}</span> 个</span>
                        </div>
                    `;
                    new cfmap.Marker({ element: marker })
                        .setLngLat(item.geometry.coordinates)
                        .addTo(this.mapboxmap);
                });
            },

            /** 遍历图片数组， */
            setImage() {
                const arr = this.iconList.concat(this.iconList2)
                arr.forEach((elet) => {
                    if (!this.mapboxmap.hasImage(elet.id)) {
                        this.addImageToMap(this.mapboxmap, elet.id, elet.url);
                    }
                });
            },

            /** 添加图标到图层 */
            addImageToMap(map, imgId, imgUrl) {
                map.loadImage(imgUrl, (error, image) => {
                    if (error) { throw error }
                    if (!image) {
                        console.log('加载图片资源出错', imgUrl);
                        return;
                    }
                    if (!map.hasImage(imgId)) {
                        map.addImage(imgId, image);
                    }
                });
            },

            //#endregion


            //#region 图层 鼠标事件

            /**
             * 给图层添加绑定事件
             * @param {Array<string>} layerIds
             */
            addMapLayerclickEvent(mapObj, layerIds) {
                const mouseEnterFun = this.mapMouseLeaveOrEnter(mapObj, true);
                const mouseLeaveFun = this.mapMouseLeaveOrEnter(mapObj, false);
                layerIds.forEach((layerId) => {
                    this.mapBindInteraction(mapObj, 'mouseenter', layerId, mouseEnterFun)
                    this.mapBindInteraction(mapObj, 'mouseleave', layerId, mouseLeaveFun)
                    const mouseClickFun = this.mapClickFunction(mapObj, layerId, (features) => {
                        if (features && features.length > 0) {
                            // 传入点查信息
                            const data = features[0].properties
                            if (!this.openDetailing) {
                                this.openDetailing = true
                                this.handleDetails(data, features[0].geometry)
                                setTimeout(() => {
                                    this.openDetailing = false
                                }, 2000);
                            }

                        } else {
                            throw new Error('点查功能未获取到图层信息');
                        }
                    });
                    this.mapBindInteraction(mapObj, 'click', layerId, mouseClickFun)
                });
            },

            /**
             * 绑定添加到地图的图层交互事件
             * @param {*} map
             * @param {string} layerId
             * @param {() => void} callback
             */
            mapBindInteraction(map, type, layerId, func) {
                map.on(type, layerId, func);
            },

            /**
             * 地图公共的图层【移入/移出】事件
             * @param {*} map 地图对象
             * @param {boolean} isEnter 是否是移入操作
             */
            mapMouseLeaveOrEnter(map, isEnter) {
                return () => {
                    map.getCanvas().style.cursor = isEnter ? 'pointer' : 'grab';
                };
            },

            /** 地图公共的点击事件 */
            mapClickFunction(map, layerId, callback) {
                return (e) => {
                    const bbox = [
                        [e.point.x - 3, e.point.y - 3],
                        [e.point.x + 3, e.point.y + 3]
                    ];
                    const features = map.queryRenderedFeatures(bbox, { layers: [layerId] });
                    // tip: 不同的应用场景不同，举例（1）点击图层后打开模态窗体（2）点击图层后打开popup框。此函数只做到将数据输出的地步
                    callback(features);
                };
            },

            /** 选中 更换服务对象图标 点击事件 */
            mapClick(info, isfly = true) {
                this.mapboxmap.removeMapStyle('highlight-style')

                if (info.geoPT && info.geoJson) {
                    if (isfly) {
                        this.flyToMap(info)
                    }

                    this.mapboxmap.addMapStyle(highlightStyle, {
                        styleid: "highlight-style",
                        isFlyTo: false,
                        isBaseMap: false,
                    });
                    const source = this.mapboxmap.getSource('highlight-sources');
                    if (source) {
                        const geoJSON = {
                            type: 'FeatureCollection',
                            features: [{
                                type: "feature",
                                geometry: info.geoJson
                            }]
                        };
                        source.setData(geoJSON);
                        setTimeout(() => {
                            this.mapboxmap.removeMapStyle('highlight-style')
                        }, 200);
                    }
                }
            },

            /** 定位 */
            flyToMap(geo) {
                if (geo.geoPT) {
                    this.mapboxmap.flyTo({ center: geo.geoPT.coordinates, zoom: 16 })
                }
            },

            // 清空图标选中样式
            clearMapSel() {
                this.mapboxmap.removeMapStyle('highlight-style')

            },
            //#endregion


            //#region 全屏
            /** 全屏 */
            setFullscreen() {
                // 隐藏顶部菜单
                let topMenu = document.querySelector('.learun-header');
                topMenu.style.display = 'none';
                // 隐藏左侧菜单
                let leftMenu = document.querySelector('.learun-sidebar');
                leftMenu.style.display = 'none';
                // 隐藏tag
                let tags = document.querySelector('.learun-tags');
                tags.style.display = 'none';

                let containerDom = document.querySelector('.learun-container');
                containerDom.style['padding-left'] = '0';
                containerDom.style['padding-top'] = '0';
                let mainDom = document.querySelector('.learun-main');
                mainDom.style['padding-top'] = '0';
                setTimeout(() => {
                    this.mapboxmap.resize(); // 重新设置地图容器的尺寸
                }, 600);
                this.isFull = true
            },

            /** 退出全屏 */
            outFullscreen() {
                // 顶部菜单
                let topMenu = document.querySelector('.learun-header');
                topMenu.style.display = '';
                // 左侧菜单
                let leftMenu = document.querySelector('.learun-sidebar');
                leftMenu.style.display = '';
                // tag
                let tags = document.querySelector('.learun-tags');
                tags.style.display = '';
                let containerDom = document.querySelector('.learun-container');
                containerDom.style['padding-left'] = '';
                containerDom.style['padding-top'] = '60px';
                let mainDom = document.querySelector('.learun-main');
                mainDom.style['padding-top'] = '40px';
                setTimeout(() => {
                    this.mapboxmap.resize(); // 重新设置地图容器的尺寸
                }, 600);
                this.isFull = false
            },
            //#endregion


        }
    }
}